var _PAYMENT_TABLE 				= "paymentTable";
var _RESERVE_PAYMENT_INDICATOR 	= "reservePaymentIndicator";

function addRowPayment(colList){
    var tblBody         = document.getElementById(_PAYMENT_TABLE);
    var size            = tblBody.rows.length;
    var newRow          = tblBody.insertRow(-1);
    newRow.height       = "30px";
    newRow.className	= "tBody";
    newRow.align		= "center";

    var tdPaymentMethod	= document.getElementById("templatePaymentMethod");
    var tdRoom			= document.getElementById("templateRoom");
    
    var newCell;
    var rowIndex        = 0;
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<a onclick="delRowPayment(this)"><img src="./images/calendar/close.gif" /></a>';
    newCell.setAttribute("align","center");
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = size+1;
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = tdPaymentMethod.innerHTML;
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<input type="text" name="colRefNo" size="10" maxlength="10" onchange="setDetailIndex(this);validateColRefNo()" class="iNL"/>';
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = tdRoom.innerHTML;
//    newCell             = newRow.insertCell(rowIndex++);
//    newCell.innerHTML   = '<input type="text" name="colDateFromTo" size="20" readonly="true" class="iDL"/>';
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<input type="text" name="colCustomerName" size="20" readonly="true" class="iDL"/>';
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<input type="text" name="colAmount" size="10" maxlength="10" onchange="setDetailIndex(this);validateColAmount()" class="iNR" onkeypress="return text_OnKeyPress_NumberOnlyAndDot();"/>';
    newCell             = newRow.insertCell(rowIndex++);
    newCell.setAttribute("display", "none");
    newCell.innerHTML   = '<input type="hidden" name="colPaymentMethodName"/>' +
    					  '<input type="hidden" name="colServicePaymentDetailId"/>' +
	  					  '<input type="hidden" name="colShiftTransId"/>'
    					  ;
    
    validateColPaymentMethod();
    /*
    var paymentMethodId = document.getElementsByName("colPaymentMethodId")[rowIndex];
	var paymentMethodName = document.getElementsByName("colPaymentMethodName")[rowIndex];
	paymentMethodName.value = paymentMethodId.options[0].text;
	*/
}

function delRowPayment(obj){
    var rowIndex        = obj.parentElement.parentElement.rowIndex-1;
    var tblBody         = document.getElementById(_PAYMENT_TABLE);
    if(confirm('Do you want to delete?')){
//    	var detailId	= document.getElementsByName("colServicePaymentDetailId")[rowIndex];
//    	var shiftTransId= document.getElementsByName("colShiftTransId")[rowIndex];
//    	alert(detailId.value);
//    	alert(shiftTransId.value);
        tblBody.deleteRow(rowIndex);
        
        calculatePaymentTotalAmount();    	
    }
}

var _ROW_INDEX = 0;
function setDetailIndex(obj){	
    if(obj){
    	var rowIndex = obj.parentElement.parentElement.rowIndex-1;
    	_ROW_INDEX   = rowIndex;
    }	
}

function validateColPaymentMethod(){
	var paymentMethodId		= document.getElementsByName("colPaymentMethodId")[_ROW_INDEX];
	var paymentMethodName	= document.getElementsByName("colPaymentMethodName")[_ROW_INDEX];
	
	paymentMethodName.value	= paymentMethodId.options[paymentMethodId.selectedIndex].text;
}

function validateColRefNo(){
	
}

function validateColAmount(){
	var obj		= document.getElementsByName("colAmount")[_ROW_INDEX];
    var val		= obj.value==''?0:parseFloat(removeCommas(obj.value));
    obj.value	= tryNumberFormatValue(val, true, 2);	
    
    calculatePaymentTotalAmount();
}

function validateColRoom(){
	var serviceDetailId = document.getElementsByName("colServiceDetailId")[_ROW_INDEX];

    var params		= "serviceDetailId=" + serviceDetailId.value;
    
    document.getElementById(_RESERVE_PAYMENT_INDICATOR).style.display = "inline";
    isdnSendRequest("reservePayment_getRoomInfoJSON.action?", params , "POST", callbackGetRoomInfo);	
}
callbackGetRoomInfo = function() {
    var ready = req.readyState;
    //  console.debug(ready);
    var jsonObject=null;
    if ( ready == 4 ){
        if(req.status == 200) {
            jsonObject=eval( "("+ req.responseText +")" );
            
			var colCustomerName 	= document.getElementsByName("colCustomerName")[_ROW_INDEX];
//			var colDateFromTo	 	= document.getElementsByName("colDateFromTo")[_ROW_INDEX];
			var colAmount	 		= document.getElementsByName("colAmount")[_ROW_INDEX];

			colCustomerName.value 	= getJSONResult(jsonObject.object.data.customerName);
//			colDateFromTo.value	 	= getJSONResult(jsonObject.object.data.serviceStartDate) + "-" + getJSONResult(jsonObject.object.data.serviceEndDate);
			colAmount.value	 		= getJSONResult(jsonObject.object.data.totalAmount);            

			calculatePaymentTotalAmount();
			
            document.getElementById(_RESERVE_PAYMENT_INDICATOR).style.display = "none";
        }
    }
};
function validatePaymentTip(){
	var obj		= document.getElementById("tip");
    var val		= obj.value==''?0:parseFloat(removeCommas(obj.value));
    obj.value	= tryNumberFormatValue(val, true, 2);	
    
	calculatePaymentTotalAmount();
}

function calculatePaymentTotalAmount(){

	var sumAmount			= document.getElementById("sumAmount");
	//calculate all totalAmount
    var tblBody             = document.getElementById(_PAYMENT_TABLE);
    var size                = tblBody.rows.length;
    var total				= 0;
    for(var i=0; i<size; i++){
    	var totalObj 		= document.getElementsByName("colAmount")[i];
    	total			   += totalObj.value==''?0:parseFloat(removeCommas(totalObj.value));
    }
    sumAmount.innerText		= tryNumberFormatValue(total, true, 2);	
    
    //calculate grand total amount
    var totalAmt 		= document.getElementById("totalAmt");
    var extraAmt 		= document.getElementById("extraAmt");
    var tip 			= document.getElementById("tip");
    var discountAmt 	= document.getElementById("discountAmt");
    var remainingAmt	= document.getElementById("remainingAmt");
    var changeAmt 		= document.getElementById("changeAmt");
    
    var calTotalAmt		= totalAmt.value==''?0:parseFloat(removeCommas(totalAmt.value));
    var calExtraAmt		= extraAmt.value==''?0:parseFloat(removeCommas(extraAmt.value));
    var calTip			= tip.value==''?0:parseFloat(removeCommas(tip.value));
    var calDiscountAmt	= discountAmt.value==''?0:parseFloat(removeCommas(discountAmt.value));
    var calRemainingAmt	= calTotalAmt + calExtraAmt + calTip - total - calDiscountAmt;
    remainingAmt.value	= tryNumberFormatValue(calRemainingAmt, true, 2);	
}

function gotoDiscountPopup() {

    var popupHeight = 200;
    var popupWidth = 350;

    var posX = parseInt((window.screen.availWidth - popupWidth) / 2);
    var posY = parseInt((window.screen.availHeight - popupHeight) / 2);

    if (posX < 0) { posX = 0; }
    if (posY < 0) { posY = 0; }

    var url		= "reservePayment_newDiscount.action";
    
    var params	= "";
    params		= params==null?'':params;
    var popup 	= window.open(url + params, 'discount', "location=no,menubar=no,resizable=no,status=yes,toolbar=no,width="+ popupWidth +",height="+ popupHeight+",scrollbars=no,left=" + posX + ",top=" + posY , "true");                
    tmp_popup 	= popup;
    return popup;
}

dojo.event.topic.subscribe("/beforeSaveReservePayment", function(event, widget){
    try{
    	/*
    	var paymentSvDetailIds = document.getElementById("colServicePaymentDetailId");
    	if(paymentSvDetailIds){
    		alert("colServicePaymentDetailId = " + paymentSvDetailIds.value);
    	} else{
	    	for(var i=0; i<paymentSvDetailIds.length; i++){
	    		alert("colServicePaymentDetailId = " + paymentSvDetailIds[i].value);
	    	}
    	}
    	var paymentNames = document.getElementById("colPaymentMethodName");
    	if(paymentNames){
    		alert("name = " + paymentNames.value);
    	} else{
	    	for(var i=0; i<paymentNames.length; i++){
	    		alert("name = " + paymentNames[i].value);
	    	}
    	}
    	*/
        var tblBody = document.getElementById(_PAYMENT_TABLE);
        var size = tblBody.rows.length;

        var tip = document.getElementById("tip");
        
    	var msgAmountMorethanZero = document.getElementById("msgAmountMorethanZero").innerText;
        
        if(tip.value != '' && parseFloat(tip.value) < 0){
	    	alert(msgAmountMorethanZero);
	    	event.cancel = true;
        }else if(size == 0) {
	    	alert("Please input payment method.");
	    	event.cancel = true;
    	}else if(!validatePaymentMethodDetail()){
	    	event.cancel = true;
       	}else{
       		if(!confirm("Do you want to save?")){
       			event.cancel = true;
       		}
       	}
    } catch(err){
         alert("Javascript error in this reserve info page beforeSaveReservePayment main function() [Error: " + err.message + "]");
         event.cancel = true;
    }
});

dojo.event.topic.subscribe("/beforeConfirmReservePayment", function(event, widget){
    try{
        var tblBody         = document.getElementById(_PAYMENT_TABLE);
        var size            = tblBody.rows.length;

        var tip				= document.getElementById("tip");
        var remainingAmt	= document.getElementById("remainingAmt");        
        
    	var msgAmountMorethanZero 	= document.getElementById("msgAmountMorethanZero").innerText;
    	var msgAmountEqualsZero 	= document.getElementById("msgAmountEqualsZero").innerText;
    	
        if(tip.value != '' && parseFloat(tip.value) < 0){
	    	alert(msgAmountMorethanZero);
	    	event.cancel = true;
        }else if(remainingAmt.value != '' && parseFloat(remainingAmt.value) != 0){
	    	alert(msgAmountEqualsZero);
	    	event.cancel = true;
        }else if(!validateCheckoutDetail()){
        	alert(document.getElementById("msgErrorNotAllCheckout").innerText);
	    	//alert("Can not confirm payment.\n Please re-check List of rooms for payment.");
	    	event.cancel = true;        	
        }else if(size == 0) {
	    	alert("Please input payment method.");
	    	event.cancel = true;
    	}else if(!validatePaymentMethodDetail()){
	    	event.cancel = true;
       	}else{
       		if(!confirm("Do you want to save?")){
       			event.cancel = true;
       		}
       	}
    }catch(err ) {
         alert("Javascript error in this reserve info page beforeSaveReservePayment main function() [Error: " + err.message + "]");
         event.cancel = true;
    }
});
function validateCheckoutDetail(){
	var arrServiceStatus = document.getElementsByName("detailServiceStatus");
	
	var size = arrServiceStatus.length;
	if(size > 0){
		for(var i=0; i<size; i++){
			if(arrServiceStatus[i].value != 'CHECKOUT'){
				return false;
			}
		}
	}
	return true;
}
function validatePaymentMethodDetail(){
    var tblBody         = document.getElementById(_PAYMENT_TABLE);
    var size            = tblBody.rows.length;
    
    var arrPaymentMethod= document.getElementsByName("colPaymentMethodId");
    var arrRefNo		= document.getElementsByName("colRefNo");
    var arrDetailId		= document.getElementsByName("colServiceDetailId");
    var arrAmount		= document.getElementsByName("colAmount");
    if(size > 0){
    	var msgAmountMorethanZero 	= document.getElementById("msgAmountMorethanZero").innerText;
    	var msgDuplicatePayment 	= document.getElementById("msgErrorDuplicatePayment").innerText;
    	var itemTmp 				= '';
    	var paymentMethodTmp 		= '';
    	var tmp						= '';
    	for(var i=0; i<size; i++){    	
    		tmp = arrPaymentMethod[i].value + arrRefNo[i].value + arrDetailId[i].value;
    		if(arrAmount[i].value == '' || parseFloat(arrAmount[i].value) == 0){
    			alert(msgAmountMorethanZero);    			
    			arrAmount[i].focus();
    			return false;
    		}else if(paymentMethodTmp != ''){
    			if(paymentMethodTmp == tmp){
    				alert(msgDuplicatePayment);
    				return false;
    			}    			
    		}    		
    		if(paymentMethodTmp == '') paymentMethodTmp = tmp;
    	}
    }
    return true;
}

window.focus();
if (!window.opener)
	window.document.write();

var openerObj = window.opener;

function refreshInfoRoomByPayment(){
	var opennerForm 						= openerObj.frmReserveInfoRoom;	
	
	var serviceHeaderId						= document.getElementById("serviceHeaderId").value;
	var servicePaymentId					= document.getElementById("servicePaymentId").value;
	var flagSave							= document.getElementById("flagSave").value;
	var flagConfirm							= document.getElementById("flagConfirm").value;
	opennerForm.serviceHeaderId.value 		= serviceHeaderId;
	opennerForm.groupId.value				= document.getElementById("groupId").value;
	if(serviceHeaderId != '' && parseInt(serviceHeaderId) > 0 && flagSave != '' && flagSave == 'Y'){
		openerObj.refreshReserveInfoRoom();	
		window.close();
	} else if(serviceHeaderId != '' && parseInt(serviceHeaderId) > 0 && flagConfirm != '' && flagConfirm == 'Y'){
		//openerObj.backReserveOverview();
		var params = "?servicePaymentId="+servicePaymentId;
		openerObj.showReservePrintReceiptPopup(params);
		window.close();			
	}
}
